package api

import (
	"context"
	"database/sql"
	"fmt"
	"ginfast/configs"
	"ginfast/db"
	"ginfast/pkg/dao"
	"ginfast/pkg/gctx"
	"ginfast/pkg/redis"
	"log"
	"runtime"

	"github.com/gin-gonic/gin"
)

type DBInit struct {
}

// IsInitHandler
func (DBInit) IsInitHandler(c *gin.Context) {
	gctx.JSONWriteData(dao.DB() != nil, c)
}

// getEnvInfo
func (DBInit) EnvInfoHandler(c *gin.Context) {
	gctx.JSONWriteData(gin.H{"sysOsName": runtime.GOOS, "goVersion": runtime.Version()}, c)
}

//
type createParam struct {
	DbCharset    string `json:"dbCharset" binding:"required"`
	DbHost       string `json:"dbHost" binding:"required"`
	DbName       string `json:"dbName" binding:"required"`
	DbPass       string `json:"dbPass" binding:"required"`
	DbPort       uint16 `json:"dbPort" binding:"required"`
	DbUser       string `json:"dbUser" binding:"required"`
	RedisAddress string `json:"redisAddress" binding:"required"`
	RedisDb      int    `json:"redisDb" binding:"required"`
	RedisPort    uint   `json:"redisPort" binding:"required"`
	RedisPass    string `json:"redisPass"`
}

// CreateDb
func (DBInit) CreateDb(c *gin.Context) {
	var p createParam
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/", p.DbUser, p.DbPass, p.DbHost, p.DbPort)
	tdb, err := sql.Open("mysql", dsn)
	if err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	res, err := tdb.ExecContext(context.TODO(), fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARSET %s COLLATE utf8mb4_general_ci", p.DbName, p.DbCharset))
	if err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	log.Println(res)
	tdb.Close()
	configs.GViper.Set("sql", &db.Options{
		Address: fmt.Sprintf("%s%s?charset=%s&parseTime=True&loc=Local", dsn, p.DbName, p.DbCharset),
		Name:    "mysql",
	})
	if err := db.Run(); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	configs.GViper.Set("redis", redis.Options{
		Address:  fmt.Sprintf("%s:%d", p.RedisAddress, p.RedisPort),
		Password: p.RedisPass,
		DB:       p.RedisDb,
	})
	configs.GViper.WriteConfig()            // 更新配置文件
	gctx.JSONWriteData(true, c)
}

func (o DBInit)Router(r *gin.RouterGroup) {
	r.GET("/isInit", o.IsInitHandler)
	r.GET("/getEnvInfo", o.EnvInfoHandler)
	r.POST("/createDb", o.CreateDb)
}
